package com.mz.auth.service;


import com.google.common.collect.Lists;
import com.mz.common.domain.SecurityUser;
import com.mz.common.domain.SysUser;
import com.mz.user.api.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义认证
 *
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuthUserService authUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 默认所有用户拥有 USER 权限
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
        grantedAuthorities.add(grantedAuthority);
        SysUser sysUser = authUserService.loginByName(username);
        // 用户存在
        if (sysUser != null) {
            return new SecurityUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword(),
                    grantedAuthorities);
        }
        // 用户不存在
        else {
            return null;
        }
    }

}
